package com.weishuang.monitor.employee.commons;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.weishuang.monitor.employee.config.ConfigParame;
import com.weishuang.monitor.employee.entity.BaseEntity;
import com.weishuang.monitor.employee.exception.RequestException;
import com.weishuang.monitor.employee.exception.TokenTimeOutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class SendUtils {

    private static final String loginUrl = ConfigParame.leaderPath + "/api/authentication";

    private static String token;

    private static String tokenAuthen = "Authorization";

    private final static Logger log = LoggerFactory.getLogger(SendUtils.class);

    /**
     * 获取token
     * @return
     * @throws RequestException
     */
    private static String getToken() throws Exception {
        Map<String, Object> parame = new HashMap<>();
        parame.put("clientId", ConfigParame.clientId);
        parame.put("clientSecret", ConfigParame.clientSecret);
        HttpResponse execute = HttpRequest.post(loginUrl).form(parame).execute();
        if (execute.isOk()) {
            String body = execute.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            Integer code = jsonObject.getInt("code");
            if (code.equals(200)) {
                token = jsonObject.getStr("data");
                return token;
            }
        }
        String msg = "登录异常:"+execute.body();
        log.error(msg);
        throw new RequestException(msg);
    }

    public static String sendRequest(String url, BaseEntity baseEntity) throws Exception {
        return sendRequest(url, baseEntity, 1);
    }

    public static String sendRequest(String url, BaseEntity baseEntity,int i) throws Exception {
        if (token == null || "".equals(token)) {
                getToken();
        }
        Map<String, Object> objectMap = baseEntity.toMap();
        HttpResponse execute = HttpRequest.post(ConfigParame.leaderPath + url +"/"+ ConfigParame.clientId)
                .header(tokenAuthen, token)
                .form(objectMap).execute();
        if (execute.isOk()) {
            String body = execute.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            Integer code = jsonObject.getInt("code");
            if (code.equals(200)) {
                return jsonObject.getStr("data");
            }else if(code.equals(405)){
                //token过期,重置为null
                log.debug("token过期地{}次重试：" + body,i);
                token = null;
                //再次执行
                if (i <=3) {
                  return sendRequest(url, baseEntity,i++);
                }else {
                    throw new TokenTimeOutException("token过期：" + body);
                }
            }
        }
        String msg = "发送异常: 请求URL："+url+"响应："+execute.body();
        log.error(msg);
        throw new RequestException(msg);
    }

}
